const connection = require('../database/dataBase')

class UserService {
  // 注册
  async register(user) {
    const { userName, password } = user
    const queryAllUsers = 'SELECT COUNT(name) FROM users WHERE name = ?;'
    const result = await connection.execute(queryAllUsers, [userName])
    if (result[0][0]['COUNT(name)'] != 0) {
      return {
        message: '用户名已存在 请直接登录',
        status: 403
      }
    } else {
      const registeredUser = 'INSERT INTO users (name,password) VALUES (?, ?);'
      await connection.execute(registeredUser, [userName, password])
      return {
        message: '注册成功',
        status: 200
      }
    }
  }
  // 登录
  async login(user) {
    const { userName, password } = user
    const queryHasUsers = `SELECT COUNT(name) FROM users WHERE name = ? AND password = ?;`
    const result = await connection.execute(queryHasUsers, [userName, password])
    if (result[0][0]['COUNT(name)'] != 0) {
      const queryUserInfo = `SELECT * FROM users WHERE name = ? AND password = ?;`
      const userInfo = await connection.execute(queryUserInfo, [userName, password])
      return {
        message: '欢迎回来~',
        status: 200,
        token: 'HANASHNF3SJA3GKD7J42SDA1#56S',
        userInfo: {
          id: userInfo[0][0].id,
          avatarUrl: userInfo[0][0].avatarUrl,
          name: userInfo[0][0].name,
          level: userInfo[0][0].level,
          accountBalance: userInfo[0][0].accountBalance
        }
      }
    } else {
      return {
        message: '账号或密码错误',
        status: 401
      }
    }
  }
}

module.exports = new UserService()